package com.niit.service;

import com.niit.mapper.UserMapper;
import com.niit.pojo.User;
import com.niit.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserService {

    public List<User> findUsers(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.findUsers();
        return users;
    }


    public List<User> searchUsers(String keyword, Integer status){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        try {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            Map<String, Object> params = new HashMap<>();
            params.put("keyword", keyword);
            params.put("status", status);
            List<User> users = mapper.searchUsers(params);
            return users;
        } finally {
            sqlSession.close();
        }
    }

    public int addUser(User user){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        try {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            int result = mapper.addUser(user);
            sqlSession.commit();
            return result;
        }
        catch (Exception e)
        {
            sqlSession.rollback();
            e.printStackTrace();
            // 记录到日志系统
            System.err.println("添加用户失败: " + e.getMessage());
            return 0;
        }
        finally
        {
            sqlSession.close();
        }
    }
    // 更新用户状态 - 修正方法实现
    public boolean updateStatus(int id, int status) {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        try {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            Map<String, Object> params = new HashMap<>();
            params.put("id", id);
            params.put("status", status);
            int result = mapper.updateStatus(params);
            sqlSession.commit();
            return result > 0;
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
            return false;
        } finally {
            sqlSession.close();
        }
    }
    // 根据ID查询用户
    public User findUserById(int id) {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        try {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            Map<String, Object> params = new HashMap<>();
            params.put("id", id);
            List<User> users = mapper.findUserById(params);
            return users != null && !users.isEmpty() ? users.get(0) : null;
        } finally {
            sqlSession.close();
        }
    }
}
